package org.kl.wx.util;

import java.sql.Timestamp;
import java.util.Map;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpMessageMatcher;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutTextMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.kl.bf.entity.basic.User;
import org.kl.bf.service.basic.UserService;
import org.kl.bf.utils.BasicConstants;
import org.kl.wx.entity.App;
import org.kl.wx.entity.EventRecord;
import org.kl.wx.entity.Groups;
import org.kl.wx.entity.WxUser;
import org.kl.wx.service.EventRecordService;
import org.kl.wx.service.GroupsService;
import org.kl.wx.service.WxUserService;

/**
 * Created by qianjia on 15/1/22.
 */
public class DemoEventHandler implements WxMpMessageHandler, WxMpMessageMatcher {

	private EventRecordService eventRecordService;

	private WxUserService wxUserService;
	private GroupsService groupsService;
	private UserService userService;
	private App app;

	public DemoEventHandler() {
	}

	public DemoEventHandler(App app, EventRecordService eventRecordService, WxUserService wxUserService, GroupsService groupsService,
			UserService userService) {
		this.app = app;
		this.eventRecordService = eventRecordService;
		this.wxUserService = wxUserService;
		this.groupsService = groupsService;
		this.userService = userService;
	}

	@Override
	public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
			WxSessionManager sessionManager) throws WxErrorException {
		EventRecord eventRecord = new EventRecord();
		eventRecord.setApp(app);
		eventRecord.setToUserName(wxMessage.getToUserName());
		eventRecord.setFromUserName(wxMessage.getFromUserName());
		eventRecord.setMsgCreateTime(new Timestamp(new DateTime(wxMessage.getCreateTime() * 1000).getMillis()));
		eventRecord.setMsgType(wxMessage.getMsgType());
		eventRecord.setEvent(wxMessage.getEvent());
		eventRecord.setEventKey(wxMessage.getEventKey());
		eventRecord.setTicket(wxMessage.getTicket());
		eventRecord.setLatitude(wxMessage.getLatitude() == null ? "" : wxMessage.getLatitude().toString());
		eventRecord.setLongitude(wxMessage.getLongitude() == null ? "" : wxMessage.getLongitude().toString());
		eventRecord.setPrecision(wxMessage.getPrecision() == null ? "" : wxMessage.getPrecision().toString());
		eventRecordService.saveEventRecord(eventRecord);
		System.out.println("来至" + eventRecord.getFromUserName() + "微信用户发往微信号" + eventRecord.getToUserName() + "的名为"
				+ eventRecord.getEvent() + "的事件已存进数据库！");
		WxUser user = wxUserService.getByAppIdAndOpenid(app.getId(), wxMessage.getFromUserName());
		WxMpXmlOutTextMessage m = null;
		switch (wxMessage.getEvent().toLowerCase()) {
		case "subscribe":
			// 添加微信用户的方法
			if (user != null) {
				if (user.getSubscribe() == BasicConstants.NO_INT) {
					user.setSubscribe(BasicConstants.YES_INT);
					wxUserService.saveWxUser(user);
					System.out.println("该openid(" + wxMessage.getFromUserName() + ")对应的微信用户重新关注成功");
				} else {
					System.out.println("该openid(" + wxMessage.getFromUserName() + ")对应的微信用户已存在系统中");
				}
			} else {
				user = new WxUser();
				user.setApp(app);
				WxMpUser wxMpUser = wxMpService.userInfo(wxMessage.getFromUserName(), "zh_CN");
				Integer groupid = (int) wxMpService.userGetGroup(wxMessage.getFromUserName());
				if (groupid == -1) {
					System.out.println("未能在微信服务器上找到对应的微信用户所在分组信息!");
					break;
				}
				Groups group = groupsService.findByAppIdAndOriginGroupId(app.getId(), groupid);
				if (group == null) {
					group = new Groups();
					group.setApp(app);
					group.setOriginGroupId(groupid);
					group.setUserCount((int) wxMpService.groupGet().get(groupid).getCount());
					group.setGroupName(wxMpService.groupGet().get(groupid).getName());
					groupsService.saveGroups(group);
				}
				user.setGroups(group);
				user.setOriginGroupId(group.getOriginGroupId());
				if (wxMpUser == null) {
					System.out.println("未能在微信服务器上找到对应的微信用户信息!");
					break;
				} else {
					user.setOpenid(wxMessage.getFromUserName());
					user.setSubscribe(BasicConstants.YES_INT);
					user.setNickname(wxMpUser.getNickname());
					user.setUserSex(StringUtils.isBlank(wxMpUser.getSex()) ? 0 : StringUtils.equals(wxMpUser.getSex(), "男") ? 1 : 2);
					user.setCity(wxMpUser.getCity());
					user.setCountry(wxMpUser.getCountry());
					user.setProvince(wxMpUser.getProvince());
					user.setLanguage(wxMpUser.getLanguage());
					user.setHeadimgurl(wxMpUser.getHeadImgUrl());
					user.setSubscribeTime(new Timestamp(wxMpUser.getSubscribeTime() * 1000));
				}
				wxUserService.saveWxUser(user);
				System.out.println("新关注用户" + user.getNickname() + "(" + user.getOpenid() + ")已成功添加进系统数据库");
			}
			m = WxMpXmlOutMessage.TEXT().content("感谢您的关注,您现在未绑定系统信息,可以点击<a href='http://www.baidu.com'>绑定</a>绑定系统用户,拥有更多功能！")
					.fromUser(wxMessage.getToUserName()).toUser(wxMessage.getFromUserName()).build();
			break;
		case "unsubscribe":
			// 删除微信用户的方法
			if (user == null) {
				System.out.println("系统中并不存在该微信用户信息!");
			} else {
				user.setSubscribe(BasicConstants.NO_INT);
				user.setUnionid(null);
				wxUserService.saveWxUser(user);
				System.out.println("服务器对应" + user.getOpenid() + "的微信用户取消关注成功!");
			}
			break;
		case "click":
			String str = "";
			if (StringUtils.isBlank(user.getUnionid())) {
				str = "您尚未绑定系统用户，不能进行该操作!点击<a href='" + BasicConstants.SYSTOM_URL + "/wxWeb/bindingWxUser?openid="
						+ wxMessage.getFromUserName() + "&appid=" + app.getId() + "&clickTime=" + new DateTime().getMillis()
						+ "'>绑定</a>前往绑定系统用户";
			} else {
				User u = userService.getUser(user.getUnionid());
				if (u == null || StringUtils.isBlank(u.getId())) {
					str = "您绑定系统用户不存在，不能进行该操作!点击<a href='" + BasicConstants.SYSTOM_URL + "/wxWeb/bindingWxUser?openid="
							+ wxMessage.getFromUserName() + "&appid=" + app.getId() + "&clickTime=" + new DateTime().getMillis()
							+ "'>绑定</a>前往绑定系统用户";
				} else {
					if (StringUtils.equals(wxMessage.getEventKey(), "wxConfig")) {
						str = "<a href='" + BasicConstants.SYSTOM_URL + "/wxWeb/" + wxMessage.getEventKey() + "?openid="
								+ wxMessage.getFromUserName() + "&appid=" + app.getId() + "&clickTime=" + new DateTime().getMillis()
								+ "'>点击前往查看相应信息</a>";
					}
				}
			}
			m = WxMpXmlOutMessage.TEXT().content(str).fromUser(wxMessage.getToUserName()).toUser(wxMessage.getFromUserName()).build();
			System.out.println("微信用户" + wxMessage.getFromUserName() + "请求" + wxMessage.getEventKey() + "的返回结果为：'" + str + "'");
			return m;
		default:
			break;
		}
		return null;
	}

	@Override
	public boolean match(WxMpXmlMessage message) {
		// TODO Auto-generated method stub
		if (StringUtils.equals("event", message.getMsgType())) {
			return true;
		} else {
			return false;
		}
	}
}
